package com.macro.mall.portal.service.impl;

import com.macro.mall.model.UmsMember;
import com.macro.mall.portal.domain.PlantingReadHistory;
import com.macro.mall.portal.repository.PlantingReadHistoryRepository;
import com.macro.mall.portal.service.PlantingReadHistoryService;
import com.macro.mall.portal.service.UmsMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 会员浏览文章记录管理Service实现类
 * Created by macro on 2018/8/3.
 */
@Service
public class PlantingReadHistoryServiceImpl implements PlantingReadHistoryService {
    @Autowired
    private PlantingReadHistoryRepository plantingReadHistoryRepository;
    @Autowired
    private UmsMemberService memberService;

    @Override
    public int create(PlantingReadHistory plantingReadHistory) {
        String trim = plantingReadHistory.getTitle().trim();
        if ("".equals(trim)) {
            return -1;
        }
        List<PlantingReadHistory> list = list(memberService.getCurrentMember().getId(), plantingReadHistory.getType());
        //如果历史搜索超过10条，删除时间最早的一条
        if (!CollectionUtils.isEmpty(list) && list.size() == 10) {
            listSort(list);
            String id = list.get(list.size() - 1).getId();
            List<String> ids = new ArrayList<>();
            ids.add(id);
            delete(ids);
        }
        List<String> collect = list.stream().map(PlantingReadHistory::getTitle).collect(Collectors.toList());
        boolean contains = collect.contains(trim);
        if (!contains) {
            UmsMember member = memberService.getCurrentMember();
            plantingReadHistory.setMemberId(member.getId());
            plantingReadHistory.setMemberUsername(member.getUsername());
            plantingReadHistory.setMemberIcon(member.getIcon());
            plantingReadHistory.setId(null);
            plantingReadHistory.setCreateTime(new Date());
            plantingReadHistoryRepository.save(plantingReadHistory);
            return 1;
        } else {
            return -1;
        }

    }

    @Override
    public int delete(List<String> ids) {
        List<PlantingReadHistory> deleteList = new ArrayList<>();
        for (String id : ids) {
            PlantingReadHistory plantingReadHistory = new PlantingReadHistory();
            plantingReadHistory.setId(id);
            deleteList.add(plantingReadHistory);
        }
        plantingReadHistoryRepository.deleteAll(deleteList);
        return ids.size();
    }

    @Override
    public List<PlantingReadHistory> list(Long memberId, Integer type) {
        UmsMember member = memberService.getCurrentMember();
//        Pageable pageable = PageRequest.of(pageNum-1, pageSize);
        return plantingReadHistoryRepository.findByMemberIdAndTypeOrderByCreateTimeDesc(member.getId(), type);
    }

    @Override
    public void clear() {
        UmsMember member = memberService.getCurrentMember();
        plantingReadHistoryRepository.deleteAllByMemberId(member.getId());
    }

    @Override
    public void clearByType(Integer type) {
        plantingReadHistoryRepository.deleteAllByType(type);
    }

    @Override
    public List<PlantingReadHistory> hotList(Integer type) {
        List<PlantingReadHistory> byType = plantingReadHistoryRepository.findByType(type);
//        byType.stream() //
//                .map(e -> { // 获取deptCode或deptAlias的Stream
//                    return flag ? e.getDeptCode() : e.getDeptName();
//                }).collect(Collectors.toMap(e -> e, e -> 1, (a, b) -> a + b)) // 获得元素出现频率的 Map，键为元素，值为元素出现的次数
//                .entrySet().stream() // 所有 entry 对应的 Stream
//                .filter(entry -> entry.getValue() > 1) // 过滤出元素出现次数大于 1 的 entry
//                .map(entry -> entry.getKey()) // 获得 entry 的键（重复元素）对应的 Stream
//                .collect(Collectors.toList()); // 转化为 List
        return null;
    }

    /**
     * 按时间排序
     *
     * @param list
     */
    private static void listSort(List<PlantingReadHistory> list) {
        Iterator<PlantingReadHistory> iterator = list.iterator();
        if (iterator.hasNext()) {
            PlantingReadHistory next = iterator.next();
            if (next == null) {
                iterator.remove();
            }
        }
        Collections.sort(list, new Comparator<PlantingReadHistory>() {
            @Override
            public int compare(PlantingReadHistory o1, PlantingReadHistory o2) {
                try {
                    if (o1.getCreateTime() == null || o2.getCreateTime() == null) {
                        return 1;
                    }
                    Date dt1 = o1.getCreateTime();
                    Date dt2 = o2.getCreateTime();

                    if (dt1.getTime() > dt2.getTime()) {
                        return -1;
                    } else if (dt1.getTime() < dt2.getTime()) {
                        return 1;
                    } else {
                        return 0;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return 0;
            }
        });
    }
}
